<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 发布者
        var shopObj = {}
        // 商品列表
        shopObj.list = []
        // 订阅
        shopObj.listen = function (key, fn) {
            if (!this.list[key]) {
                this.list[key] = []
            }
            this.list[key].push(fn);
        }
        // 发布消息
        shopObj.publish = function (key) {
            var fns = this.list[key];
            for (let i = 0, fn; fn = fns[i]; i++) {
                // 执行订阅的fn
                fn.apply(this, arguments);
            }
        }
        // 添加订阅
        shopObj.listen("huawei", function (brand, model) {
            console.log(brand, model);
        })
        shopObj.listen('apple', function (brand, model) {
            console.log(brand, model);
        })
        // 商家发布消息
        shopObj.publish("huawei", 'p30');
        shopObj.publish('apple', 'iphone 11')

        // 代码重构
        var event = {
            list: [],
            listen: function (key, fn) {
                if (!this.list[key]) {
                    this.list[key] = []
                }
                this.list[key].push(fn);
            },
            publish: function (key) {
                var fns = this.list[key];
                for (let i = 0, fn; fn = fns[i]; i++) {
                    fn.apply(this, arguments)
                }
            }
        }
        // 观察者对象初始化
        var initEvent = function (obj) {
            // for(let i in event) {
            //     obj[i] = event[i];
            // }
            // 也可以使用这种方法复制对象
            Object.assign(obj, event)
        }
        // 发布者
        var shopObj2 = {}
        initEvent(shopObj2);
        // 添加订阅
        shopObj2.listen("huawei", function (brand, model) {
            console.log(brand, model);
        })
        shopObj2.listen('apple', function (brand, model) {
            console.log(brand, model);
        })
        // 商家发布消息
        shopObj2.publish("huawei", 'p30');
        shopObj2.publish('apple', 'iphone 11')
    </script>
</body>

</html>